<?php
declare (strict_types=1);

namespace app\common\logic;


use think\response\Json;

/**
 * @mixin \think\Model
 * 微信小程序相关功能示例
 */
class Wechat
{
    protected string $appid = '';  //  小程序appid
    protected string $secret = ''; //  小程序secret

    public function __construct(string $appid = '', string $secret = '')
    {
        $this->appid = $appid ?: config('wechat.wx_mini.appid');
        $this->secret = $secret ?: config('wechat.wx_mini.secret');
    }

    /**
     * @notes 获取openid
     * @param string $js_code 小程序登录时获取的code
     * @return array
     */
    public function getOpenid(string $js_code = ''): array
    {
        // 拼接请求地址
        $uri = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->secret}&js_code={$js_code}&grant_type=authorization_code";
        return json_decode(curlGet($uri), true);
    }

    /**
     * @notes 获取微信运动步数
     * @param string $session_key 会话密钥
     * @param string $encryptedData 加密数据
     * @param string $iv 加密算法的初始向量
     * @return array|int
     */
    public function getWxRunData(string $session_key, string $encryptedData, string $iv): array|int
    {
        $data = [];
        $errCode = $this->decryptData($session_key, $encryptedData, $iv, $data);
        if ($errCode == 0) {
            return is_array($data) ? $data : json_decode($data, true);
        } else {
            return $errCode;
        }
    }

    /**
     * @notes 获取微信接口调用凭证，有效期限7200s
     * @return array|Json
     */
    public function getAccessToken(): array|Json
    {
        $uri = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->secret}";
        $res = json_decode(curlGet($uri), true);
        if (isset($res['access_token'])) {
            return $res;
        } else {
            return ['code' => 0, 'msg' => '获取失败！'];
        }
    }

    /**
     * @notes 获取微信用户手机号
     * @param string $akToken
     * @param string $phone_code
     * @return array
     */
    public function getPhoneNumber(string $akToken, string $phone_code): array
    {
        $uri = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" . $akToken;
        return curlPost($uri, json_encode(['code' => $phone_code]));
    }

    /**
     * @notes 数据解密
     * @param string $session_key 会话密钥
     * @param string $encryptedData 加密数据
     * @param string $iv 加密算法的初始向量
     * @return array|int
     */
    protected function decryptData(string $session_key, string $encryptedData, string $iv, &$data): array|int
    {
        if (strlen($session_key) != 24) {
            return ErrorCode::$IllegalAesKey;
        }
        $aesKey = base64_decode($session_key);


        if (strlen($iv) != 24) {
            return ErrorCode::$IllegalIv;
        }
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result);
        if ($dataObj == NULL) {
            return ErrorCode::$IllegalBuffer;
        }

        if ($dataObj->watermark->appid != $this->appid) {
            return ErrorCode::$IllegalBuffer;
        }
        $data = $result;
        return ErrorCode::$OK;
    }

}
